<template>
    <div class="group-tree">
        <div class="tree-wrapper">
            <a-tree
                :tree-data="treeData"
                :expanded-keys.sync="expandedKeys"
                :selected-keys="selectedKeys"
                show-icon
                @select="onSelect"
            >
                <template #title="{ title, key, isLeaf, ...node }">
                    <template v-if="isLeaf">
                        <div style="margin: 0 0;">
                            <DeviceCard
                                :device="node"
                                :is-selected="selectedKeys.includes(key)"
                                :is-online="getDeviceIsOnline(node)"
                                :tooltip-content="getDeviceTooltip(node)"
                                @edit="editNode(key, true)"
                                @delete="deleteNode(key)"
                                @export="exportDevice(key)"
                            />
                        </div>
                    </template>
                    <template v-else>
                        <div class="tree-node-title">
                            <span>
                                <a-icon type="folder" theme="filled" style="margin-right: 8px; color: #1890ff;" />
                                {{ title }}
                            </span>
                            <div v-if="shouldShowGroupActions(key)" class="tree-node-actions">
                                <a-tooltip v-if="!isLeaf" title="添加设备">
                                    <a-icon type="plus-circle-o" @click.stop="() => addDeviceToGroup(key)" />
                                </a-tooltip>
                                <a-tooltip v-if="!isLeaf" title="导入设备">
                                    <a-icon type="import" @click.stop="() => importDevice(key)" />
                                </a-tooltip>                                                                
                                <a-tooltip v-if="!isDefaultGroup(key)" title="编辑">
                                    <a-icon type="edit" @click.stop="() => editNode(key, isLeaf)" />
                                </a-tooltip>
                                <a-tooltip v-if="!isDefaultGroup(key)" title="删除">
                                    <a-icon type="delete" @click.stop="() => deleteNode(key)" />
                                </a-tooltip>
                            </div>
                        </div>
                    </template>
                </template>
            </a-tree>
        </div>
        
        <!-- Modals -->
        <GroupModal
            :visible.sync="groupModalVisible"
            title="分组管理"
            :initial-name="editingGroupName"
            @ok="handleGroupOk"
            @cancel="handleGroupCancel"
        />
        <ManageGroupsModal
            :visible.sync="manageGroupsModalVisible"
            :groups="allRootGroups"
            @add="handleGroupAdd"
            @edit="handleGroupEdit"
            @delete="handleGroupDelete"
        />
        <DeviceModal
            :visible.sync="deviceModalVisible"
            :title="deviceModalTitle"
            :initial-data="editingDeviceData"
            @ok="handleDeviceOk"
            @cancel="handleDeviceCancel"
        />

        <div class="group-tree-actions">
            <a-button type="dashed" icon="plus" @click="showAddGroupModal">添加分组</a-button>
            <a-button type="dashed" icon="setting" @click="showManageGroupsModal">管理分组</a-button>
        </div>
    </div>
</template>

<script>
import GroupModal from './GroupTree/components/GroupModal.vue'
import ManageGroupsModal from './GroupTree/components/ManageGroupsModal.vue'
import DeviceModal from './GroupTree/components/DeviceModal.vue'
import DeviceCard from './GroupTree/components/DeviceCard.vue'
import tabManager from '@/api/tab-manager'
import { getGatewayHardwareInfo } from '@/config/gateway-config'
import { mapActions, mapGetters } from 'vuex'
import { openFolderDialog } from '@/api/TabAxios/base'

export default {
    name: 'GroupTree',
    components: {
        GroupModal,
        ManageGroupsModal,
        DeviceModal,
        DeviceCard
    },
    data() {
        return {
            selectedKeys: [],
            expandedKeys: [],
            treeData: [],
            // Modal states
            groupModalVisible: false,
            editingGroupName: '',
            editingGroupKey: null,
            manageGroupsModalVisible: false,
            deviceModalVisible: false,
            deviceModalTitle: '添加设备',
            editingDeviceData: null,
            editingDeviceKey: null,
            addingToGroupKey: null,
            
            // 设备相关变量
            currentDeviceId: null,
            currentDeviceName: '',
            deviceHardwareInfo: {}, // 存储每个设备的硬件信息 {deviceId: hardwareInfo}
            currentDeviceIdNum: 0,
            // 重试相关
            retryCount: 0,
            maxRetries: 5,
            retryDelay: 2000, // 2秒
            retryTimer: null
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo']),
        
        allRootGroups() {
            return this.treeData.map(g => ({ key: g.key, title: g.title }))
        },
        selectedGroup() {
            // 获取当前选中的分组
            if (this.selectedKeys.length === 0) return null
            
            const selectedKey = this.selectedKeys[0]
            // 如果是分组，直接返回
            const group = this.treeData.find(g => g.key === selectedKey)
            if (group) return group
            
            // 如果是设备，找到其父分组
            for (const group of this.treeData) {
                if (group.children && group.children.find(d => d.key === selectedKey)) {
                    return group
                }
            }
            return null
        },
        selectedDevice() {
            // 获取当前选中的设备
            if (this.selectedKeys.length === 1) {
                const selectedKey = this.selectedKeys[0]
                return this.treeData.find(d => d.key === selectedKey)
            }
            return null
        },
        filteredDevicesInSelectedGroup() {
            if (!this.selectedGroup || !this.selectedGroup.children) return []
            return this.selectedGroup.children.filter(device => device.isLeaf)
        }
    },
    beforeDestroy() {
        // 清理定时器
        if (this.retryTimer) {
            clearTimeout(this.retryTimer)
            this.retryTimer = null
        }
    },
    async created() {
        // 初始加载分组树
        await this.loadGroupTree()
    },
    methods: {
        ...mapActions('groupTree', ['setSelectedDevice', 'setSelectedGroup', 'clearSelected', 'updateTreeData']),
        // === 辅助函数：从key中提取ID ===
        extractIdFromKey(key) {
            if (key.startsWith('group-')) {
                return key.replace('group-', '')
            }
            if (key.startsWith('device-')) {
                return key.replace('device-', '')
            }
            return key
        },
        
        // === 辅助函数：从ID生成key ===
        generateGroupKey(id) {
            return `group-${id}`
        },
        
        generateDeviceKey(id) {
            return `device-${id}`
        },
        
        async loadGroupTree() {
            try {
                // 获取完整的分组树数据（包含设备）
                const response = await tabManager.group.getTreeWithDevices()
                
                console.log('🔍 [GroupTree] 获取完整分组树响应:', response)
                // 检查响应状态 - 统一返回格式：code=0表示成功
                if (response && response.code === 0) {
                    // 处理后端返回的数据
                    const groups = response.data || []
                    
                    // 将后端返回的分组数据添加到树中
                    this.treeData = groups.map(group => ({
                        title: group.title || group.name,
                        key: this.generateGroupKey(group.id), // 使用辅助函数生成key
                        id: group.id,
                        scopedSlots: { title: 'title' },
                        children: Array.isArray(group.devices)  // 使用devices字段
                            ? group.devices.map(device => ({
                                ...device,
                                key: this.generateDeviceKey(device.id), // 使用辅助函数生成key
                                title: device.name || device.title,
                                isLeaf: true,
                                scopedSlots: { title: 'title' }
                            }))
                            : []
                    }))
                    
                    // 更新 Vuex 中的树数据
                    this.updateTreeData(this.treeData)
                    
                    console.log('🔍 [GroupTree] Tree data constructed:', this.treeData)
                    
                    // 验证每个节点的 isLeaf 属性和key唯一性
                    const allKeys = []
                    this.treeData.forEach(group => {
                        console.log(`🔍 [GroupTree] Group ${group.key} (${group.title}):`, {
                            isLeaf: group.isLeaf,
                            hasChildren: !!group.children,
                            childrenCount: group.children ? group.children.length : 0
                        })
                        allKeys.push(group.key)
                        if (group.children) {
                            group.children.forEach(device => {
                                console.log(`  🔍 [GroupTree] Device ${device.key} (${device.title}):`, {
                                    isLeaf: device.isLeaf,
                                    id: device.id,
                                    originalDevice: device
                                })
                                allKeys.push(device.key)
                            })
                        }
                    })
                    
                    // 检查key重复
                    const duplicateKeys = allKeys.filter((key, index) => allKeys.indexOf(key) !== index)
                    if (duplicateKeys.length > 0) {
                        console.error('🚨 [GroupTree] Duplicate keys found:', duplicateKeys)
                    } else {
                        console.log('✅ [GroupTree] All keys are unique')
                    }

                    // 默认展开和选中第一个分组
                    if (this.treeData.length > 0) {
                        const firstGroup = this.treeData[0]
                        this.expandedKeys = [firstGroup.key]
                        
                        // 如果第一个分组有设备，选中分组和第一个设备
                        if (firstGroup.children && firstGroup.children.length > 0) {
                            const firstDevice = firstGroup.children[0]
                            this.selectedKeys = [firstGroup.key, firstDevice.key]
                            this.setCurrentDevice(firstDevice.key, firstDevice.title || firstDevice.name)
                            
                            // 存储到 Vuex
                            this.setSelectedDevice({
                                id: firstDevice.id,
                                key: firstDevice.key,
                                name: firstDevice.title || firstDevice.name,
                                ...firstDevice
                            })
                            
                            this.setSelectedGroup({
                                id: firstGroup.id,
                                key: firstGroup.key,
                                name: firstGroup.title,
                                ...firstGroup
                            })
                            // 需要调用selectDevice方法
                            this.selectDevice(firstDevice.key, firstDevice)
                        } else {
                            // 如果第一个分组没有设备，选中分组本身
                            this.selectedKeys = [firstGroup.key]
                            this.setCurrentDevice(null, '')
                            
                            // 存储到 Vuex
                            this.setSelectedDevice(null)
                            this.setSelectedGroup({
                                id: firstGroup.id,
                                key: firstGroup.key,
                                name: firstGroup.title,
                                ...firstGroup
                            })
                        }
                    }
                    
                    console.log('✅ [GroupTree] 分组树初始化成功:', this.treeData)
                    
                    // 重置重试计数
                    this.retryCount = 0
                } else {
                    throw new Error(response?.msg || '获取分组树失败')
                }
            } catch (error) {
                console.error('❌ [GroupTree] 获取分组树失败:', error)
                
                // 重试逻辑
                if (this.retryCount < this.maxRetries) {
                    this.retryCount++
                    console.log(`🔄 [GroupTree] 尝试重新获取分组树 (${this.retryCount}/${this.maxRetries})`)
                    
                    this.retryTimer = setTimeout(() => {
                        this.loadGroupTree()
                    }, this.retryDelay)
                } else {
                    console.error('❌ [GroupTree] 达到最大重试次数，停止重试')
                    this.$message.error('获取分组树失败，请检查网络连接')
                }
            }
        },
        // --- Tree Events ---
        onSelect(keys, event) {
            console.log('🔍 [GroupTree] onSelect called:', { keys, event })
            console.log('🔍 [GroupTree] Current selectedKeys before:', this.selectedKeys)
            
            // 阻止默认的选择行为，完全由我们控制
            if (keys.length === 0) return
            
            const selectedKey = keys[0]
            const node = this.findNodeByKey(selectedKey, this.treeData)
            
            console.log('🔍 [GroupTree] Selected node:', node)
            console.log('🔍 [GroupTree] Selected key:', selectedKey)
            console.log('🔍 [GroupTree] Is leaf?', node?.isLeaf)
            
            if (!node) {
                console.error('🚨 [GroupTree] Node not found for key:', selectedKey)
                return
            }
            
            // 立即阻止Tree组件的默认选择行为
            event.preventDefault && event.preventDefault()
            
            if (node.isLeaf) {
                // 选中设备
                console.log('🔍 [GroupTree] This is a device, selecting device')
                this.selectDevice(selectedKey, node)
            } else {
                // 选中分组
                console.log('🔍 [GroupTree] This is a group, selecting group')
                this.selectGroup(selectedKey, node)
            }
            
            console.log('🔍 [GroupTree] Final selectedKeys:', this.selectedKeys)
            
            // 返回 false 来阻止默认行为
            return false
        },
        
        selectDevice(deviceKey, deviceNode) {
            console.log('🔍 [GroupTree] selectDevice called:', deviceKey, deviceNode.id)
            
            // 选中设备
            this.selectedKeys = [deviceKey]
            this.setCurrentDevice(deviceKey, deviceNode.title || deviceNode.name)
            this.currentDeviceIdNum = deviceNode.id
            // 找到父分组并确保展开
            const parentGroup = this.findParentGroup(deviceKey, this.treeData)
            if (parentGroup) {
                console.log('🔍 [GroupTree] Device parent group:', parentGroup.key)
                if (!this.expandedKeys.includes(parentGroup.key)) {
                    this.expandedKeys = [...this.expandedKeys, parentGroup.key]
                }
            }
            
            // 存储到 Vuex
            this.setSelectedDevice({
                id: deviceNode.id, // 直接使用 deviceNode.id
                key: deviceKey,
                name: deviceNode.title || deviceNode.name,
                ...deviceNode
            })
            
            if (parentGroup) {
                this.setSelectedGroup({
                    id: parentGroup.id,
                    key: parentGroup.key,
                    name: parentGroup.title,
                    ...parentGroup
                })
            }
            
            console.log('🔍 [GroupTree] Device selected, selectedKeys set to:', this.selectedKeys)
            this.$emit('select', deviceKey)
        },
        
        selectGroup(groupKey, groupNode) {
            console.log('🔍 [GroupTree] selectGroup called:', groupKey)
            
            // 展开分组
            if (!this.expandedKeys.includes(groupKey)) {
                this.expandedKeys = [...this.expandedKeys, groupKey]
            }
            
            // 如果分组有设备，选中分组和第一个设备
            if (groupNode.children && groupNode.children.length > 0) {
                const firstDevice = groupNode.children[0]
                console.log('🔍 [GroupTree] Group has devices, selecting group and first device:', { groupKey, deviceKey: firstDevice.key })
                
                // 同时选中分组和第一个设备
                this.selectedKeys = [groupKey, firstDevice.key]
                this.setCurrentDevice(firstDevice.key, firstDevice.title || firstDevice.name)
                
                // 存储到 Vuex
                this.setSelectedDevice({
                    id: firstDevice.id,
                    key: firstDevice.key,
                    name: firstDevice.title || firstDevice.name,
                    ...firstDevice
                })
                
                this.setSelectedGroup({
                    id: groupNode.id,
                    key: groupKey,
                    name: groupNode.title,
                    ...groupNode
                })
                
                this.$emit('select', firstDevice.key)
            } else {
                // 如果分组没有设备，选中分组本身
                console.log('🔍 [GroupTree] Group has no devices, selecting group itself')
                this.selectedKeys = [groupKey]
                this.setCurrentDevice(null, '')
                
                // 存储到 Vuex
                this.setSelectedDevice(null)
                this.setSelectedGroup({
                    id: groupNode.id,
                    key: groupKey,
                    name: groupNode.title,
                    ...groupNode
                })
                
                this.$emit('select', groupKey)
            }
        },

        // --- Modal Triggers ---
        showAddGroupModal() {
            this.editingGroupKey = null
            this.editingGroupName = ''
            this.groupModalVisible = true
        },
        showManageGroupsModal() {
            this.manageGroupsModalVisible = true
        },

        // --- Add/Edit/Delete Operations ---
        addDeviceToGroup(parentKey) {
            console.log('🔍 [GroupTree] addDeviceToGroup called with key:', parentKey)
            
            this.deviceModalTitle = '添加设备'
            this.addingToGroupKey = parentKey
            this.editingDeviceKey = null
            
            // 找到分组节点并获取整型groupId
            const groupNode = this.findNodeByKey(parentKey, this.treeData)
            console.log('🔍 [GroupTree] Found group node:', groupNode)
            
            const groupId = groupNode ? groupNode.id : -1
            console.log('🔍 [GroupTree] Group ID for device creation:', groupId)
            
            this.editingDeviceData = {
                gatewayType: 'WG01',
                name: '',
                allowDeviceRename: false,
                allowVariableRename: false,
                groupId: groupId  // 使用整型groupId
            }
            
            console.log('🔍 [GroupTree] Opening device modal with data:', this.editingDeviceData)
            this.deviceModalVisible = true
        },
        editNode(key, isLeaf) {
            console.log('🔍 [GroupTree] editNode called:', { key, isLeaf })
            
            const node = this.findNodeByKey(key, this.treeData)
            console.log('🔍 [GroupTree] Found node for editing:', node)
            
            if (!node) {
                console.error('🚨 [GroupTree] Node not found for editing:', key)
                return
            }
            
            if (isLeaf) {
                console.log('🔍 [GroupTree] Editing device')
                this.deviceModalTitle = '编辑设备'
                this.editingDeviceKey = key
                this.addingToGroupKey = null
                
                // 找到设备所属的分组并获取整型groupId
                const parentGroup = this.findParentGroup(key, this.treeData)
                console.log('🔍 [GroupTree] Device parent group:', parentGroup)
                
                const groupId = parentGroup ? parentGroup.id : null
                console.log('🔍 [GroupTree] Parent group ID:', groupId)
                
                this.editingDeviceData = {
                    id: node.id,
                    gatewayType: node.gatewayType || 'WG01',
                    name: node.title || node.name || '',
                    allowDeviceRename: node.allowDeviceRename || false,
                    allowVariableRename: node.allowVariableRename || false,
                    groupId: groupId  // 使用整型groupId
                }
                
                console.log('🔍 [GroupTree] Device editing data:', this.editingDeviceData)
                this.deviceModalVisible = true
            } else {
                console.log('🔍 [GroupTree] Editing group')
                this.editingGroupKey = key
                this.editingGroupName = node.title
                this.groupModalVisible = true
            }
        },
        deleteNode(key) {
            console.log('🔍 [GroupTree] deleteNode called with key:', key)
            
            const node = this.findNodeByKey(key, this.treeData)
            console.log('🔍 [GroupTree] Found node for deletion:', node)
            
            if (!node) {
                console.error('🚨 [GroupTree] Node not found for deletion:', key)
                return
            }
            
            if (node.isLeaf) {
                // 删除设备
                this.$confirm({
                    title: '确认删除',
                    content: '确定要删除该设备吗？',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        // 找到设备所属的分组
                        const parentGroup = this.findParentGroup(key, this.treeData)
                        const deviceNode = this.findNodeByKey(key, this.treeData)
                        if (parentGroup && deviceNode) {
                            // 提取实际的ID用于API调用
                            const groupId = this.extractIdFromKey(parentGroup.key)
                            // 使用设备节点的实际 id 属性，而不是从 key 中提取
                            const deviceId = deviceNode.id || this.extractIdFromKey(key)
                            
                            console.log('🔍 [GroupTree] 删除设备:', { 
                                groupId, 
                                deviceId, 
                                deviceKey: key,
                                deviceNode: deviceNode 
                            })
                            
                            tabManager.group.deleteDeviceFromGroup(groupId, deviceId)
                                .then(response => {
                                    // 检查响应状态 - 统一返回格式：code=0表示成功
                                    if (response && response.code === 0) {
                                        this.$message.success('设备删除成功')
                                        this.removeNodeByKey(key, this.treeData)
                                        if (this.selectedKeys.includes(key)) {
                                            // 选中第一个分组
                                            if (this.treeData.length > 0) {
                                                this.selectGroup(this.treeData[0].key, this.treeData[0])
                                            }
                                        }
                                    } else {
                                        throw new Error(response?.msg || '设备删除失败')
                                    }
                                })
                                .catch(error => {
                                    console.error('❌ [GroupTree] 设备删除失败:', error)
                                    
                                    // 检查是否是CefSharp相关错误
                                    if (error.message && error.message.includes('cefSharp')) {
                                        this.$message.error('CefSharp环境不可用，请检查后端服务')
                                    } else {
                                        this.$message.error(error.message || '删除失败，请重试')
                                    }
                                })
                        }
                    }
                })
            } else {
                // 删除分组
                if (this.isDefaultGroup(key)) {
                    this.$message.error('默认分组不能删除')
                    return
                }
                this.$confirm({
                    title: '确认删除',
                    content: '确定要删除该分组吗？该操作将一并删除其下的所有内容。',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        // 获取分组节点
                        const groupNode = this.findNodeByKey(key, this.treeData)
                        if (!groupNode || !groupNode.id) {
                            this.$message.error('无法获取分组ID')
                            return
                        }
                        
                        const groupId = this.extractIdFromKey(key)
                        console.log('🔍 [GroupTree] 删除分组ID:', groupId)
                        tabManager.group.tree.delete(groupId)
                            .then(response => {
                                // 检查响应状态 - 统一返回格式：code=0表示成功
                                if (response && response.code === 0) {
                                    this.$message.success(response.msg)
                                    
                                    // 从本地树形数据中删除分组
                                    this.removeNodeByKey(key, this.treeData)
                                    
                                    // 如果删除的是当前选中的分组，切换到第一个分组
                                    if (this.selectedKeys.includes(key)) {
                                        if (this.treeData.length > 0) {
                                            this.selectGroup(this.treeData[0].key, this.treeData[0])
                                        }
                                    }
                                } else {
                                    throw new Error(response?.msg || '分组删除失败')
                                }
                            })
                            .catch(error => {
                                console.error('❌ [GroupTree] 分组删除失败:', error)
                                
                                // 检查是否是CefSharp相关错误
                                if (error.message && error.message.includes('cefSharp')) {
                                    this.$message.error('CefSharp环境不可用，请检查后端服务')
                                } else {
                                    this.$message.error(error.message || '删除失败，请重试')
                                }
                            })
                    }
                })
            }
        },

        // --- Modal Event Handlers ---
        async handleGroupOk(name) {
            try {
                if (this.editingGroupKey) {
                    // 更新分组 - 获取分组节点以获取整型id
                    const node = this.findNodeByKey(this.editingGroupKey, this.treeData)
                    if (!node || !node.id) {
                        throw new Error('无法获取分组ID')
                    }
                    
                    const groupId = this.extractIdFromKey(this.editingGroupKey)
                    console.log('🔍 [GroupTree] 更新分组:', { id: groupId, title: name })
                    // 更新分组 - 使用整型id和新名称
                    await tabManager.group.tree.update(groupId, name)
                    this.$message.success('分组更新成功')
                    
                    // 更新本地树形数据
                    node.title = name
                } else {
                    // 创建分组
                    const response = await tabManager.group.tree.create({ title: name })
                    
                    // 检查响应状态 - 统一返回格式：code=0表示成功
                    if (response && response.code === 0) {
                        this.$message.success('分组创建成功')
                        
                        // 将新分组添加到树形数据中 - response.data直接是整型groupId
                        const groupId = response.data
                        const newGroupNode = {
                            title: name,
                            id: groupId,
                            key: this.generateGroupKey(groupId),  // key使用字符串形式的ID
                            scopedSlots: { title: 'title' },
                            children: []
                        }
                        this.treeData.push(newGroupNode)
                        
                        // 自动展开新创建的分组
                        this.expandedKeys.push(newGroupNode.key)
                    } else {
                        throw new Error(response?.msg || '分组创建失败')
                    }
                }
                
                this.groupModalVisible = false
            } catch (error) {
                console.error('分组操作失败:', error)
                this.$message.error(error.message || '操作失败，请重试')
            }
        },
        handleGroupCancel() {
            this.groupModalVisible = false
            this.editingGroupKey = null
            this.editingGroupName = ''
        },
        async handleGroupAdd(newGroup) {
            try {
                const response = await tabManager.group.tree.create({ title: newGroup.title })
                
                console.log('🔍 [GroupTree] 分组创建响应:', response)
                // 检查响应状态 - 统一返回格式：code=0表示成功
                if (response && response.code === 0) {
                    this.$message.success('分组创建成功')
                    
                    // 将新分组添加到树形数据中 - response.data直接是整型groupId
                    const groupId = response.data
                    const newGroupNode = {
                        title: newGroup.title,
                        id: groupId,
                        key: this.generateGroupKey(groupId),  // key使用字符串形式的ID
                        scopedSlots: { title: 'title' },
                        children: []
                    }
                    this.treeData.push(newGroupNode)
                    
                    // 自动展开新创建的分组
                    this.expandedKeys.push(newGroupNode.key)
                    
                    // 不再自动关闭管理分组弹框，让用户可以继续添加更多分组
                    // this.manageGroupsModalVisible = false
                } else {
                    throw new Error(response?.msg || '分组创建失败')
                }
            } catch (error) {
                console.error('分组创建失败:', error)
                this.$message.error(error.message || '创建失败，请重试')
            }
        },
        async handleGroupEdit({ key, title }) {
            try {
                // 获取分组节点以获取整型id
                const node = this.findNodeByKey(key, this.treeData)
                if (!node || !node.id) {
                    throw new Error('无法获取分组ID')
                }
                
                const groupId = this.extractIdFromKey(key)
                console.log('🔍 [GroupTree] 编辑分组:', { id: groupId, title })
                const response = await tabManager.group.tree.update(groupId, title)
                
                // 检查响应状态 - 统一返回格式：code=0表示成功
                if (response && response.code === 0) {
                    this.$message.success('分组更新成功')
                    
                    // 更新本地树形数据
                    node.title = title
                } else {
                    throw new Error(response?.msg || '分组更新失败')
                }
            } catch (error) {
                console.error('分组更新失败:', error)
                this.$message.error(error.message || '更新失败，请重试')
            }
        },
        async handleGroupDelete(key) {
            try {
                const groupId = this.extractIdFromKey(key)
                const response = await tabManager.group.tree.delete(groupId)
                
                // 检查响应状态 - 统一返回格式：code=0表示成功
                if (response && response.code === 0) {
                    this.$message.success('分组删除成功')
                    
                    // 从本地树形数据中删除分组
                    this.removeNodeByKey(key, this.treeData)
                    
                    // 如果删除的是当前选中的分组，切换到默认分组
                    if (this.selectedKeys.includes(key)) {
                        if (this.treeData.length > 0) {
                            this.selectGroup(this.treeData[0].key, this.treeData[0])
                        }
                    }
                } else {
                    throw new Error(response?.msg || '分组删除失败')
                }
            } catch (error) {
                console.error('分组删除失败:', error)
                this.$message.error(error.message || '删除失败，请重试')
            }
        },
        async handleDeviceOk(formData) {
            try {
                if (this.editingDeviceKey) {
                    // 编辑设备 - 找到设备所属的分组
                    const parentGroup = this.findParentGroup(this.editingDeviceKey, this.treeData)
                    const deviceNode = this.findNodeByKey(this.editingDeviceKey, this.treeData)
                    if (parentGroup && deviceNode) {
                        const groupId = this.extractIdFromKey(parentGroup.key)
                        // 使用设备节点的实际 id 属性，而不是从 key 中提取
                        const deviceId = deviceNode.id || this.extractIdFromKey(this.editingDeviceKey)
                        
                        console.log('🔍 [GroupTree] 编辑设备:', { 
                            groupId, 
                            deviceId, 
                            deviceKey: this.editingDeviceKey,
                            deviceNode: deviceNode 
                        })
                        
                        const response = await tabManager.group.updateDeviceInGroup(groupId, deviceId, formData)
                        
                        // 检查响应状态 - 统一返回格式：code=0表示成功
                        if (response && response.code === 0) {
                            this.$message.success('设备编辑成功')
                            
                            // 更新本地树形数据
                            const node = this.findNodeByKey(this.editingDeviceKey, this.treeData)
                            if (node) {
                                node.title = formData.name
                                node.name = formData.name
                                node.gatewayType = formData.gatewayType
                                // 保存设备硬件信息到本地存储
                                this.setDeviceHardwareInfo(this.editingDeviceKey, formData)
                                node.allowDeviceRename = formData.allowDeviceRename
                                node.allowVariableRename = formData.allowVariableRename
                            }
                        } else {
                            throw new Error(response?.msg || '设备编辑失败')
                        }
                    }
                } else if (this.addingToGroupKey) {
                    // 添加设备到分组
                    const groupNode = this.findNodeByKey(this.addingToGroupKey, this.treeData)
                    const groupId = this.extractIdFromKey(this.addingToGroupKey)
                    
                    console.log('🔍 [GroupTree] 添加设备请求数据:', formData)
                    const response = await tabManager.group.addDeviceToGroup(groupId, formData)
                    
                    // 检查响应状态 - 统一返回格式：code=0表示成功
                    if (response && response.code === 0 && response.data) {
                        this.$message.success('设备添加成功')
                        
                        // 将新设备添加到对应的分组中
                        const newDevice = {
                            title: formData.name,
                            key: this.generateDeviceKey(response.data.id || response.data.key || Date.now()),
                            name: formData.name,
                            online: false,
                            gatewayType: formData.gatewayType,
                            allowDeviceRename: formData.allowDeviceRename,
                            allowVariableRename: formData.allowVariableRename,
                            isLeaf: true,
                            scopedSlots: { title: 'title' },
                            id: response.data.id || response.data
                        }
                        
                        // 保存设备硬件信息到本地存储
                        this.setDeviceHardwareInfo(newDevice.key, formData)
                        
                        // 找到对应的分组并添加设备
                        if (groupNode) {
                            if (!groupNode.children) {
                                groupNode.children = []
                            }
                            groupNode.children.push(newDevice)
                            
                            // 自动展开分组
                            if (!this.expandedKeys.includes(this.addingToGroupKey)) {
                                this.expandedKeys.push(this.addingToGroupKey)
                            }
                        }
                        
                        console.log('✅ [GroupTree] 设备添加成功:', newDevice)
                    } else {
                        throw new Error(response?.msg || '设备添加失败')
                    }
                }
                
                this.deviceModalVisible = false
            } catch (error) {
                console.error('❌ [GroupTree] 设备操作失败:', error)
                
                // 检查是否是CefSharp相关错误
                if (error.message && error.message.includes('cefSharp')) {
                    this.$message.error('CefSharp环境不可用，请检查后端服务')
                } else {
                    this.$message.error(error.message || '操作失败，请重试')
                }
            }
        },
        handleDeviceCancel() {
            this.deviceModalVisible = false
            this.editingDeviceKey = null
            this.editingDeviceData = null
            this.addingToGroupKey = null
        },

        // --- Helper Methods ---
        findNodeByKey(key, tree) {
            for (const node of tree) {
                if (node.key === key) return node
                if (node.children) {
                    const found = this.findNodeByKey(key, node.children)
                    if (found) return found
                }
            }
            return null
        },
        removeNodeByKey(key, tree) {
            for (let i = 0; i < tree.length; i++) {
                if (tree[i].key === key) {
                    tree.splice(i, 1)
                    return true
                }
                if (tree[i].children) {
                    if (this.removeNodeByKey(key, tree[i].children)) return true
                }
            }
            return false
        },

        // --- Public Methods for Parent ---
        toggleGroupExpansion() {
            if (this.expandedKeys.length > 0) {
                this.expandedKeys = []
            } else {
                this.expandedKeys = this.treeData.filter(node => !node.isLeaf).map(node => node.key)
            }
        },
        showEditModal(key) {
            const node = this.findNodeByKey(key, this.treeData)
            if (node) this.editNode(key, node.isLeaf)
        },
        confirmDelete(key) {
            this.deleteNode(key)
        },
        async fetchGroupTree() {
            const res = await tabManager.group.tree.getTree()
            this.treeData = res.data
        },
        async fetchDevicesByGroup(groupId) {
            const res = await tabManager.group.getDevicesByGroup(groupId)
            return res.data
        },
        findParentGroup(key, tree) {
            for (const node of tree) {
                if (node.children) {
                    for (const child of node.children) {
                        if (child.key === key) {
                            return node
                        }
                    }
                    const found = this.findParentGroup(key, node.children)
                    if (found) return found
                }
            }
            return null
        },
        getConnectionStatusClass(group) {
            // 根据分组中设备的连接状态返回样式类
            if (!group.children || group.children.length === 0) {
                return 'status-disconnected'
            }
            
            // 检查是否有设备连接
            const hasConnectedDevice = group.children.some(device => {
                // 这里可以根据实际需求判断设备连接状态
                // 暂时模拟：设备001和PLC-001为已连接状态
                return device.key === 'device-001' || device.key === 'plc-001'
            })
            
            return hasConnectedDevice ? 'status-connected' : 'status-disconnected'
        },
        getConnectionStatusText(group) {
            if (!group.children || group.children.length === 0) {
                return '无设备'
            }
            
            const hasConnectedDevice = group.children.some(device => {
                return device.key === 'device-001' || device.key === 'plc-001'
            })
            
            return hasConnectedDevice ? '已连接' : '未连接'
        },
        getSerialPortsCount(group) {
            if (!group.children || group.children.length === 0) {
                return 0
            }
            
            // 统计分组中所有设备的串口数量
            return group.children.reduce((total, device) => {
                const hardwareInfo = this.getDeviceHardwareInfo(device.key || device.id)
                return total + (hardwareInfo.serialPortCount || 0)
            }, 0)
        },
        getNetworkPortsCount(group) {
            if (!group.children || group.children.length === 0) {
                return 0
            }
            
            // 统计分组中所有设备的网口数量（Io数量作为网口数量）
            return group.children.reduce((total, device) => {
                const hardwareInfo = this.getDeviceHardwareInfo(device.key || device.id)
                return total + (hardwareInfo.ioCount || 0)
            }, 0)
        },
        getDeviceConnectionClass(device) {
            // 根据设备连接状态返回样式类
            const hardwareInfo = this.getDeviceHardwareInfo(device.key || device.id)
            if (!hardwareInfo || !hardwareInfo.updateMode) {
                return 'status-disconnected'
            }
            
            // 检查设备是否连接
            const isConnected = hardwareInfo.updateMode === 'ethernet' || hardwareInfo.updateMode === 'serialport'
            
            return isConnected ? 'status-connected' : 'status-disconnected'
        },
        getDeviceConnectionText(device) {
            return device.online ? '已连接' : '未连接'
        },
        getDeviceTooltip(device) {
            if (!device) return ''
            const status = this.getDeviceConnectionText(device)
            const hardwareInfo = this.getDeviceHardwareInfo(device.key || device.id)
            return `
                <div style='min-width:200px;'>
                    <div><b>名称：</b>${device.name || device.title || ''}</div>
                    <div><b>类型：</b>${device.gatewayType || ''}</div>
                    <div><b>连接状态：</b>${status}</div>
                    <div><b>串口数量：</b>${hardwareInfo.serialPortCount || 0}</div>
                    <div><b>Io数量：</b>${hardwareInfo.ioCount || 0}</div>
                    <div><b>描述：</b>${hardwareInfo.hardwareDescription || ''}</div>
                </div>
            `
        },
        getDeviceIsOnline(device) {
            return !!device.online
        },
        
        // 设备硬件信息管理方法
        getDeviceHardwareInfo(deviceId) {
            // 获取特定设备的硬件信息，如果没有则返回默认值
            const savedInfo = this.deviceHardwareInfo[deviceId]
            if (savedInfo) {
                return savedInfo
            }
            // 如果没有保存的信息，返回默认的WG01配置
            return getGatewayHardwareInfo('WG01')
        },
        
        setDeviceHardwareInfo(deviceId, hardwareInfo) {
            // 设置特定设备的硬件信息
            this.$set(this.deviceHardwareInfo, deviceId, hardwareInfo)
        },
        
        updateDeviceHardwareInfo(deviceId, updates) {
            // 更新特定设备的硬件信息（部分更新）
            const currentInfo = this.getDeviceHardwareInfo(deviceId)
            const updatedInfo = { ...currentInfo, ...updates }
            this.setDeviceHardwareInfo(deviceId, updatedInfo)
        },
        
        getCurrentDeviceInfo() {
            // 获取当前选中设备的信息
            if (!this.currentDeviceId) return null
            return {
                id: this.currentDeviceId,
                name: this.currentDeviceName,
                hardwareInfo: this.getDeviceHardwareInfo(this.currentDeviceId)
            }
        },
        
        setCurrentDevice(deviceId, deviceName) {
            // 设置当前设备
            this.currentDeviceId = deviceId
            this.currentDeviceName = deviceName
        },
        
        // 更新设备在线状态
        updateDeviceStatus(statusInfo) {
            console.log('🔄 [GroupTree] 更新设备状态:', statusInfo)
            console.log('🔍 [GroupTree] 当前树数据:', this.treeData)
            console.log('🔍 [GroupTree] 状态信息详情:', {
                deviceId: statusInfo.deviceId,
                deviceIdType: typeof statusInfo.deviceId,
                deviceKey: statusInfo.deviceKey,
                online: statusInfo.online,
                onlineType: typeof statusInfo.online
            })
            
            if (!statusInfo || (!statusInfo.deviceId && !statusInfo.deviceKey)) {
                console.error('🚨 [GroupTree] 无效的状态信息:', statusInfo)
                return
            }
            
            try {
                const { deviceId, deviceKey, online } = statusInfo
                
                // 先输出所有可用设备信息用于对比
                console.log('🔍 [GroupTree] 所有可用设备:', this.getAllDevicesInfo())
                
                // 在树形数据中查找并更新设备状态
                const updateDeviceInTree = (nodes, isOnline) => {
                    for (const node of nodes) {
                        if (node.children) {
                            // 在分组的子设备中查找
                            for (const device of node.children) {
                                console.log('🔍 [GroupTree] 检查设备:', {
                                    deviceInTree: device,
                                    deviceId: device.id,
                                    deviceIdType: typeof device.id,
                                    deviceKey: device.key,
                                    targetDeviceId: deviceId,
                                    targetDeviceIdType: typeof deviceId,
                                    targetDeviceKey: deviceKey,
                                    idMatch: device.id === deviceId,
                                    idStrictMatch: device.id === deviceId,
                                    idLooseMatch: device.id == deviceId,
                                    keyMatch: device.key === deviceKey
                                })
                                
                                // 尝试更灵活的匹配
                                const idMatches = device.id === deviceId || device.id == deviceId || String(device.id) === String(deviceId)
                                const keyMatches = device.key === deviceKey
                                
                                if (idMatches || keyMatches) {
                                    console.log('✅ [GroupTree] 找到设备，更新状态:', {
                                        deviceName: device.name || device.title,
                                        oldStatus: device.online,
                                        newStatus: isOnline,
                                        matchedBy: idMatches ? 'ID' : 'Key'
                                    })
                                    
                                    // 使用 Vue 的响应式更新方法
                                    this.$set(device, 'online', isOnline)
                                    console.log('🔄 [GroupTree] 设备状态已使用$set更新:', device.online)
                                    
                                    // 如果是当前选中的设备，同时更新 Vuex
                                    if (this.selectedDeviceInfo && 
                                        (this.selectedDeviceInfo.id === deviceId || this.selectedDeviceInfo.key === deviceKey)) {
                                        console.log('🔄 [GroupTree] 同时更新 Vuex 中的选中设备状态')
                                        this.$store.commit('groupTree/updateSelectedDeviceStatus', isOnline)
                                    }
                                    
                                    return true
                                }
                            }
                            // 递归查找子节点
                            if (updateDeviceInTree(node.children, isOnline)) {
                                return true
                            }
                        }
                    }
                    return false
                }
                
                const updated = updateDeviceInTree(this.treeData, online)
                
                if (updated) {
                    console.log('✅ [GroupTree] 设备状态更新成功')
                    // 触发视图更新
                    this.$forceUpdate()
                } else {
                    console.warn('⚠️ [GroupTree] 未找到要更新的设备:', statusInfo)
                    console.log('🔍 [GroupTree] 所有设备信息:', this.getAllDevicesInfo())
                }
                
            } catch (error) {
                console.error('❌ [GroupTree] 更新设备状态失败:', error)
            }
        },
        
        // 辅助方法：获取所有设备信息用于调试
        getAllDevicesInfo() {
            const devices = []
            const extractDevices = nodes => {
                for (const node of nodes) {
                    if (node.children) {
                        for (const device of node.children) {
                            devices.push({
                                id: device.id,
                                key: device.key,
                                name: device.name || device.title,
                                online: device.online
                            })
                        }
                        extractDevices(node.children)
                    }
                }
            }
            extractDevices(this.treeData)
            return devices
        },

        // 辅助方法：判断是否为默认分组
        isDefaultGroup(key) {
            const node = this.findNodeByKey(key, this.treeData)
            const isDefault = node && (node.title === '默认分组' || node.name === '默认分组')
            console.log('🔍 [GroupTree] 判断是否为默认分组:', { key, title: node?.title, name: node?.name, isDefault })
            return isDefault
        },

        // 辅助方法：判断是否显示分组操作按钮
        shouldShowGroupActions(key) {
            // 根据选中的设备判断是否属于当前分组
            if (this.selectedKeys.length === 0) return false
            
            const selectedKey = this.selectedKeys[0]
            const selectedNode = this.findNodeByKey(selectedKey, this.treeData)
            
            if (!selectedNode) return false
            // 如果选中的是设备，判断设备是否属于当前分组
            if (selectedNode.isLeaf) {
                const parentGroup = this.findParentGroup(selectedKey, this.treeData)
                const belongsToGroup = parentGroup && parentGroup.key === key
                return belongsToGroup
            } else {
                // 如果选中的是分组，判断是否是当前分组
                const isCurrentGroup = selectedKey === key
                return isCurrentGroup
            }
        },
        async exportDevice(key) {
            console.log('🔍 [GroupTree] 导出设备:', key)
            try {
                const result = await openFolderDialog()
                if (result.code === 0) {
                    const data = JSON.parse(result.data)
                    if (data.folderPath.length === 0) {
                        return
                    }
                    const parentGroup = this.findParentGroup(key, this.treeData)
                    const groupId = parentGroup ? parentGroup.id : null
                    const jsonData = {
                        groupDeviceId: groupId.toString(),
                        exportFolder: data.folderPath,
                        exportFileName: this.currentDeviceName, // 获取设备名称
                        deviceId: this.currentDeviceIdNum
                    }
                    const res = await tabManager.group.exportDevice(JSON.stringify(jsonData))
                    if (res && res.code === 0) {
                        this.$message.success('导出设备成功')
                    } else {
                        this.$message.error('导出设备失败: ' + (res.msg || '未知错误'))
                    }
                } else {
                    this.$message.error('导出设备失败')
                }
            } catch (error) {
                console.error('❌ [GroupTree] 导出设备失败:', error)
                this.$message.error('导出设备失败')
            }
        },
        async importDevice(key) {
            console.log('🔍 [GroupTree] 导入设备:', key)
            try {
                const result = await openFolderDialog()
                console.log('🔍 [GroupTree] 打开文件夹结果:', result)
                if (result.code === 0) {
                    const data = JSON.parse(result.data)
                    if (data.folderPath.length === 0) {
                        return
                    }
                    
                    const groupId = this.selectedGroup?.id
                    console.log('🔍 [GroupTree] 导入设备groupId:', groupId)
                    const jsonData = {
                        groupDeviceId: groupId.toString(),
                        importFolder: data.folderPath
                    }
                    const res = await tabManager.group.importDevice(JSON.stringify(jsonData))
                    console.log('🔍 [GroupTree] 导入设备结果:', res)
                    if (res && res.code === 0) {
                        this.$message.success('导入设备成功')
                        // 刷新设备树
                        this.loadGroupTree()
                    } else {
                        this.$message.error('导入设备失败: ' + (res.msg || '未知错误'))
                    }
                }
            } catch (error) {
                console.error('❌ [GroupTree] 选择设备文件夹失败:', error)
                this.$message.error('选择设备文件夹失败')
            }
        }
    }
}
</script>

<style scoped>
.group-tree {
    height: 100%;
    display: flex;
    flex-direction: column;
}
.tree-wrapper {
    flex: none;
    height: 90%;
    overflow: auto;
    padding: 16px;
    border-right: 1px solid #e8e8e8;
}
.devices-cards-wrapper {
    flex: 1;
    overflow: auto;
    padding: 16px;
}
.devices-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.devices-header h3 {
    margin: 0;
    color: #333;
}
.group-info {
    display: flex;
    align-items: center;
    gap: 16px;
}
.group-info .info-item {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 12px;
}
.group-info .info-item .anticon {
    margin-right: 4px;
    font-size: 12px;
}
.devices-cards-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
}
.device-card {
    background-color: #fff;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
}
.device-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}
.device-card.selected {
    border: 2px solid #1890ff;
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}
.device-card-header {
    padding: 16px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.device-title {
    display: flex;
    align-items: center;
}
.device-icon {
    margin-right: 8px;
    font-size: 16px;
}
.device-name {
    font-size: 16px;
    font-weight: 600;
}
.device-actions {
    display: flex;
    gap: 8px;
}
.device-actions .anticon {
    font-size: 14px;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: background-color 0.3s ease;
}
.device-actions .anticon:hover {
    background-color: rgba(255, 255, 255, 0.2);
}
.device-card-content {
    padding: 16px;
}
.device-info-grid {
    display: grid;
    gap: 8px;
}
.info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
}
.info-row:last-child {
    border-bottom: none;
}
.info-label {
    font-size: 12px;
    color: #666;
    font-weight: 500;
}
.info-value {
    font-size: 12px;
    color: #333;
    font-weight: 600;
}
.device-card-footer {
    padding: 12px 16px;
    background-color: #f8f9fa;
    border-top: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
}
.connection-indicator {
    display: flex;
    align-items: center;
    gap: 4px;
}
.connection-indicator .anticon {
    font-size: 12px;
}
.status-connected {
    color: #52c41a;
}
.status-disconnected {
    color: #ff4d4f;
}
.hardware-summary {
    display: flex;
    align-items: center;
    gap: 12px;
    color: #666;
}
.empty-devices {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 48px;
    background-color: #f8f9fa;
    border-radius: 8px;
    color: #6c757d;
    grid-column: 1 / -1;
}
.empty-devices .anticon {
    font-size: 32px;
    margin-bottom: 16px;
    color: #ccc;
}
.empty-devices span {
    margin-bottom: 16px;
    font-size: 14px;
}
.tree-node-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}
.tree-node-actions {
    display: inline-block;
    color: #1890ff;
}
.tree-node-actions .anticon {
    margin-left: 8px;
    cursor: pointer;
}
.group-tree-actions {
    padding: 16px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    gap: 12px;
    margin-top: auto;
}
.group-tree-actions .ant-btn {
    flex: 1;
}
.devices-cards-container.single {
    display: flex;
    justify-content: center;
    align-items: flex-start;
}

/* 让设备节点的treeitem高度自适应DeviceCard */
::v-deep .ant-tree-treenode-leaf {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    min-height: unset !important;
    height: auto !important;
}

/* 彻底隐藏 antd tree 的选中高亮背景 */
::v-deep .ant-tree-treenode-leaf.ant-tree-treenode-selected > .ant-tree-node-content-wrapper,
::v-deep .ant-tree-treenode.ant-tree-treenode-selected > .ant-tree-node-content-wrapper {
    background: none !important;
    box-shadow: none !important;
}

/* 让内容撑满treeitem */
::v-deep .ant-tree-node-content-wrapper {
    padding: 0 !important;
    height: auto !important;
    min-height: unset !important;
}
</style> 